using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppNetworkTestAndToEmail
{
    /// <summary>
    /// 检测URL是否连通
    /// </summary>
    /// 创建时间：2022-12-16 13:55:51。作者： 
    internal class PingURLHelpter
    {

        /// <summary>
        /// ping url，返回耗时（毫秒）。返回处理状态HttpStatus
        /// </summary>
        /// <param name="url">Http  url</param>
        /// <param name="timeout">预设的超时时间,单位（秒)</param>
        /// <returns></returns>
        internal static PingResult PingHttpURL(string url, int timeout = 15)
        {
            PingResult result = new PingResult();
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            try
            {
                Console.WriteLine("正在ping地址:" + url);
                HttpClient httpClient = new HttpClient();
                httpClient.Timeout = TimeSpan.FromSeconds(timeout);

                //httpClient.MaxResponseContentBufferSize = 
                //string url = "https://www.dongchedi.com/auto/params-carIds-x-31";

                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
                stopwatch.Start();
                var responseMessage = httpClient.Send(requestMessage);
                result.HttpStatusCode = (int)responseMessage.StatusCode;

                stopwatch.Stop();
                //检测耗时，毫秒
                result.Tested_time_consuming = stopwatch.ElapsedMilliseconds;

                LogHelpter.AddLog(url + "响应状态码:" + result.HttpStatusCode + ",耗时(毫秒)" + result.Tested_time_consuming);
                return result;
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                result.HttpStatusCode = 7777;
                result.Tested_time_consuming = stopwatch.ElapsedMilliseconds;

                var ex1 = ex.InnerException ?? ex;
                var ex2 = ex1.InnerException ?? ex1;
                LogHelpter.AddLog(url + "请求异常：" + ex2.Message, null, "error");
                return result;
            }
        }

        /// <summary>
        /// 检测ip、网址是否可访问。不需要端口号。
        /// ip格式：192.168.1.226;
        /// 网址格式：www.baidu.com
        /// </summary>
        /// <param name="ipAddress">ip地址</param>
        /// <param name="timeout">预设的超时时间,单位（毫秒)</param>
        /// <returns></returns>
        /// 创建时间：2022-12-16 14:01:02。作者：王浩力
        internal static PingResult TcpIpPing(string host, int timeout = 3000)
        {
            try
            {
                var pingHandle = new System.Net.NetworkInformation.Ping();
                var result = pingHandle.Send(host, timeout);
                if (result.Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    string msg = $"原{host}，解析地址{result.Address}连接成功，返回字节{result.Buffer.Length}，响应毫秒数{result.RoundtripTime}";
                    LogHelpter.AddLog(msg);
                    return new PingResult() { HttpStatusCode = 200, Tested_time_consuming = result.RoundtripTime };
                }
                else
                {
                    string msg = $"原{host}，解析地址{result.Address}访问失败 ,响应毫秒数{result.RoundtripTime}";
                    LogHelpter.AddLog(msg);
                }
                return new PingResult() { HttpStatusCode = 500, Tested_time_consuming = 0 };
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog("检测异常2，" + ex.Message);
                return new PingResult() { HttpStatusCode = 500, Tested_time_consuming = 0 };
            }
        }

    }

    /// <summary>
    /// 返回值
    /// </summary>
    internal struct PingResult
    {
        /// <summary>
        /// 返回的响应状态码，返回200表示连接成功。
        /// </summary>
        public int HttpStatusCode { get; set; }

        /// <summary>
        /// 耗时，单位毫秒
        /// </summary>
        public long Tested_time_consuming { get; set; }

    }
}
